<?php
/**
 * @Author: feidao@ibantang.com, 2020, all rights reserved
 * @Date: 2020/3/3
 * @Time: 7:13 PM
 * @Brief:
 */

namespace Core\Common\Base;

use Core\Common\Route\Request;

/**
 * 分布式锁
 * Class DisLocker
 * @package Core\Common\Base
 */
class DisLocker
{
    private static $pool = [];

    /**
     * @var Jaguar
     */
    private $kv;

    /**
     * 新建一个分布式锁对象
     * DisLocker constructor.
     * @param $kv
     */
    private function __construct($kv)
    {
        $this->kv = $kv;
    }

    /**
     * 获取锁对象
     * @param $name string 配置名
     * @return DisLocker
     */
    public static function getInstance($name)
    {
        $mars = Request::isRunningInMars();
        $uniqId = $name;
        if ($mars) {
            $uniqId .= "_mars";
        }
        if (isset(self::$pool[$uniqId])) {
            return self::$pool[$uniqId];
        }
        self::$pool[$uniqId] = new self(Jaguar::getInstance($name));
        return self::$pool[$uniqId];
    }

    /**
     * 获取一个锁
     * @param $name string 锁的名字
     * @param $seconds int 锁的有效期(秒)
     * @return string 成功后返回锁ID
     */
    public function accquire($name, $seconds)
    {
        return $this->kv->HGET($name, $seconds);
    }

    /**
     * 释放锁
     * @param $name string 锁的名字
     * @param $lockId string 锁的唯一ID
     * @return int 返回1代表成功，其他代表失败
     */
    public function release($name, $lockId)
    {
        return $this->kv->HDEL($name, $lockId);
    }

    /**
     * 强制释放锁
     * @param $name string
     * @return mixed|null
     */
    public function forceRelease($name)
    {
        return $this->kv->DEL($name);
    }

    /**
     * 查询锁的ID
     * @param $name
     * @return mixed|null
     */
    public function query($name)
    {
        return $this->kv->GET($name);
    }
}
